﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TCPServer
{
    public  class TCPServer
    {
        private static byte[] result = new byte[1024];
        private static int myProt = 8093;   //端口  
        private static string ipdiz = "10.7.234.101";
        private static Encoding encode = Encoding.Default;
        static Socket serverSocket;
        static List<byte> data = new List<byte>();
        /// <summary>
        /// 获得TCPServer传值
        /// </summary>
        public void GetTCPServer()
        {
            //服务器IP地址  
            IPAddress ip = IPAddress.Parse(ipdiz);
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址：端口  
            serverSocket.Listen(10);    //设定最多10个排队连接请求  
            Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
            //创建线程获取其中状态
            Thread myThread = new Thread(ListenClientConnect);
            myThread.Start();
            Console.ReadLine();
        }
        /// <summary>
        /// TCPServer：对指定的IP和端口进行传值
        /// </summary>
        public void GetPassing()
        {
            //设定服务器IP地址
            IPAddress ip = IPAddress.Parse("117.71.48.112");
            //配置传输模式
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 2206)); //配置服务器IP与端口  
                Console.WriteLine("连接服务器成功");
            }
            catch
            {
                Console.WriteLine("连接服务器失败，请按回车键退出！");
                return;
            }
            //通过clientSocket连接成功后返回数据
            int receiveLength = clientSocket.Receive(result);
            Console.WriteLine("返回数据：{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
            // 通过 clientSocket 发送数据
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    Thread.Sleep(1000);    //等待1秒钟  
                    string sendMessage = "client send Message Hellp" + DateTime.Now;//要发送的消息
                    clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));//对消息进行编码并且对消息进行发送
                    Console.WriteLine("向服务器发送消息：{0}" + sendMessage);
                }
                catch
                {
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    break;
                }
            }
            Console.WriteLine("发送完毕，按回车键退出");
            Console.ReadLine();
        }

        /// <summary>  
        /// 监听客户端连接  
        /// </summary>  
        private static void ListenClientConnect()
        {
            while (true)
            {

                Socket clientSocket = serverSocket.Accept();
                clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientSocket);
            }
        }

        /// <summary>  
        /// 接收消息  
        /// </summary>  
        /// <param name="clientSocket"></param>  
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;//把object类型传参转为Socket类型
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据  
                    int receiveNumber = myClientSocket.Receive(result);
                    string receiveData = Receive(myClientSocket, 5000); //5秒接受一次
                    StreamWriter sw = File.AppendText("C:\\ces3.txt");
                    //sw.WriteLine("接收客户端{0}消息{1}receiveNumber{2}十六进制{3}", myClientSocket.RemoteEndPoint.ToString(), Encoding.Default.GetString(result, 0, receiveNumber), receiveNumber, byteToHexStr(result));
                    //sw.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(),byteToHexStr(result, receiveNumber));
                    Console.WriteLine("接收客户端{0}消息{1}|{3}时间{2}", myClientSocket.RemoteEndPoint.ToString(), Convert.ToChar(receiveNumber), DateTime.Now, receiveData);
                    sw.Flush();
                    sw.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }
        /// <summary>
        /// 接收数据:对数据进行解析
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string Receive(Socket socket, int timeout)
        {
            string result = string.Empty;
            socket.ReceiveTimeout = timeout;
            //List<byte> data = new List<byte>();
            byte[] buffer = new byte[1024];
            int length = 0;
            try
            {
                while ((length = socket.Receive(buffer)) > 0)
                {
                    for (int j = 0; j < length; j++)
                    {
                        data.Add(buffer[j]);
                        //Console.WriteLine(buffer[j]);
                    }
                    if (length < buffer.Length)
                    {
                        break;
                    }
                }
            }
            catch { }
            if (data.Count > 0)
            {
                result = encode.GetString(data.ToArray(), 0, data.Count);
            }
            return result;
        }
    }
}
